import { App } from 'vue';

export default (app: App) => {
    app.directive('dragMove', (el, binding) => {
        // 拖拽区域
        const dragArea = el.querySelector(binding.value.dragArea);
        // 获取当前浏览器窗口宽高（高度减去任务栏）
        const clientWidth = document.documentElement.clientWidth;
        const clientHeight = document.documentElement.clientHeight - 40;

        // 按下鼠标处理事件
        dragArea.onmousedown = (e: MouseEvent) => {
            // 按下时鼠标位置
            const mouseX = e.clientX;
            const mouseY = e.clientY;
            // 按下时元素相对偏移量
            const elX = el.offsetLeft;
            const elY = el.offsetTop;

            // 鼠标移动事件
            document.onmousemove = (e) => {
                let currentMouseX = e.clientX;
                let currentMouseY = e.clientY;
                // 限制定位不能移出浏览器（预留10px的空间）
                if (currentMouseX <= 10) {
                    currentMouseX = 10;
                } else if (currentMouseX >= clientWidth - 10) {
                    currentMouseX = clientWidth;
                }
                if (currentMouseY <= 10) {
                    currentMouseY = 10;
                } else if (currentMouseY >= clientHeight - 10) {
                    currentMouseY = clientHeight;
                }
                // 计算需要偏移的距离
                const left = currentMouseX - mouseX;
                const top = currentMouseY - mouseY;

                // 样式修改
                el.style.left = elX + left + 'px';
                el.style.top = elY + top + 'px';
            };

            // 鼠标松开事件
            document.onmouseup = () => {
                document.onmousemove = null;
                document.onmouseup = null;
            };
        };
    });
};
